import { _decorator, Component, Sprite, resources, SpriteFrame, Node, Prefab, instantiate, Label } from 'cc';
import NBSlotsMachine, { SlotsMachineRollLevel } from './NBSlotsMachine';
const { ccclass, property } = _decorator;

@ccclass('test')
export class test extends Component {
    @property(NBSlotsMachine)
    slotsMachine: NBSlotsMachine = null;


    //结果区域
    @property(Node)
    resultsNode: Node = null;
    @property(Prefab)
    item:Prefab = null;

    private resultsDatas = []

    private datas : Map<number,[]> = new Map();
    start() {
        this.slotsMachine.slotsSlots.forEach((v,column)=>{
            v.rollHook.refreshItem = async (node, index) => {
                let sp: Sprite = node.getChildByName('SpriteSplash').getComponent(Sprite);
                let path = this.getPath(column,index);
                let lb: Label = node.getChildByName('Label').getComponent(Label);
                lb.string = index + '';
                sp.spriteFrame = await this.loadSprite(path);
            }
            v.rollHook.continueRoll = () => {
                this.calculateTargetIndexs();
                return Boolean(this.resultsDatas.length);
            }
        })
        this.slotsMachine.slotsMachineHook.machineRollComplete = ()=>{
            this.textLB.string = '开始滚动'
            this.rolling = false;
        }
        this.slotsMachine.nonotifyItemChanged();
    }

    private getPath(column , index){
        let d:any = this.datas.get(column);
        let pathIndex = -1;
        if(d){
            for(let i = 0 ; i < d.length ; ++i){
                if(d[i].itemIndex == index){
                    pathIndex = d[i].pathIndex;
                    break
                }
            }
        }
        if(pathIndex != -1 && pathIndex != undefined && pathIndex >= 0){
            return `pic/ui_icon_${pathIndex}/spriteFrame`
        }else {
            let pathIndex = Math.floor(Math.random() * (8 - 1)) + 1;
            return `pic/ui_icon_${pathIndex}/spriteFrame`;
        }
    }

    private rolling = false;
    click() {
        if(this.rolling){
            return;
        }
        this.rolling = true;
        this.textLB.string = '正在滚动'
        //this.calculateTargetIndexs();
        this.slotsMachine.launchMachine();
    }

    private calculateTargetIndexs(){
        const targetIndexs = this.slotsMachine.calculateTargetIndexs();
        this.datas.clear();
        let startIndex = 0;
        targetIndexs.forEach((v , index)=>{
            const slots = this.slotsMachine.slotsSlots[index];
            const slotsNum = slots.rows;
            let arr:any = [];
            //this.datas[index] = [];
            for(let i = 0 ; i < slotsNum ; ++i){
                let pathIndex = this.resultsDatas[startIndex]; 
                let itemIndex = v + i;
                arr.push({pathIndex,itemIndex});
               startIndex += 1;
            }
            this.datas.set(index,arr);
            console.log(arr)
        })
        
    }

    loadSprite(path): Promise<SpriteFrame> {
        return new Promise((r) => {
            resources.load(path, SpriteFrame, (err: any, texture: SpriteFrame) => {
                r(texture)
            });
        })
    }


    private tempDatas = []
    async chooseItem(target,index){
        const node = instantiate(this.item);
        this.resultsNode.addChild(node);
        const sp = node.getChildByName('sp').getComponent(Sprite);
        let key = `pic/ui_icon_${index}/spriteFrame`;
        this.tempDatas.push(index);
        sp.spriteFrame = await this.loadSprite(key);
      
    }

    clearDatas(){
        this.resultsNode.removeAllChildren();
        this.resultsDatas.length = 0;
        this.tempDatas.length = 0;
    }

    @property(Label)
    levelLable: Label = null;
    private level = SlotsMachineRollLevel.NormalSpeed
    clickLevel(){
        if(this.level == SlotsMachineRollLevel.NormalSpeed){
            this.level = SlotsMachineRollLevel.FastSpeed;
            this.levelLable.string = '3级速度'
        }else if(this.level == SlotsMachineRollLevel.FastSpeed){
            this.level = SlotsMachineRollLevel.LowSpeed;
            this.levelLable.string = '1级速度'
        }else if(this.level == SlotsMachineRollLevel.LowSpeed){
            this.level = SlotsMachineRollLevel.NormalSpeed;
            this.levelLable.string = '2级速度'
        }
        this.slotsMachine.speedLevel = this.level;
    }

    @property(Label)
    textLB: Label = null;


    //模拟数据延迟回来
    private commiteDatas(){
        this.tempDatas.forEach((v)=>{
            this.resultsDatas.push(v);
        })
    }
}
